package top.onedream.buildsmallsoftware.controller


import org.springframework.web.bind.annotation.PostMapping
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.bind.annotation.RequestParam
import org.springframework.web.bind.annotation.RestController
import top.onedream.buildsmallsoftware.cfg.exception.CustomException
import top.onedream.buildsmallsoftware.enums.ExceptionEnum
import top.onedream.buildsmallsoftware.model.user.User
import top.onedream.buildsmallsoftware.service.UserService
import top.onedream.buildsmallsoftware.util.TokenUtil

@RestController
@RequestMapping("/user")
class LoginController(
    private val loginService: UserService,
    private val tokenUtil: TokenUtil
) {

    /**
     * 登录
     * @param [username] 用户名
     * @return [String?]
     */
    @PostMapping("/login")
    fun login(
        @RequestParam   username: String
    ): String? {
        val userByUsername: User = loginService.getUserByUsername(username) ?: return null
        return tokenUtil.createToken(userByUsername) ?: throw CustomException(ExceptionEnum.LOGIN_ERROR)
    }
}